package edu.cmu.cs.stage3.alice.authoringtool.util;

import edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool;

/**
 * @author Jason Pratt
 */
public class RectangleAnimator extends javax.swing.JWindow implements Runnable {
	protected AuthoringTool authoringTool;
	protected java.awt.Rectangle sourceBounds;
	protected java.awt.Rectangle targetBounds;
	protected long duration = 300;
	protected long startTime;

	public RectangleAnimator( AuthoringTool authoringTool ) {
		this.authoringTool = authoringTool;
	}

	public java.awt.Color getColor() {
		return getBackground();
	}

	public void setColor( java.awt.Color color ) {
		setBackground( color );
	}

	public long getDuration() {
		return duration;
	}

	public void setDuration( long duration ) {
		this.duration = duration;
	}

	public java.awt.Rectangle getSourceBounds() {
		return sourceBounds;
	}

	public void setSourceBounds( java.awt.Rectangle r ) {
		sourceBounds = r;
	}

	public java.awt.Rectangle gettargetBounds() {
		return targetBounds;
	}

	public void setTargetBounds( java.awt.Rectangle r ) {
		targetBounds = r;
	}

	public void animate( java.awt.Rectangle sourceBounds, java.awt.Rectangle targetBounds ) {
		setSourceBounds( sourceBounds );
		setTargetBounds( targetBounds );

		setBounds( sourceBounds );
		setVisible( true );

		startTime = System.currentTimeMillis();
		authoringTool.getScheduler().addEachFrameRunnable( this );
	}

	public void animate( java.awt.Rectangle sourceBounds, java.awt.Rectangle targetBounds, java.awt.Color color ) {
		setColor( color );
		animate( sourceBounds, targetBounds );
	}

	public void run() {
		long time = System.currentTimeMillis();
		long dt = time - startTime;
		if( dt <= duration ) {
			double portion = ((double)dt)/((double)duration);
			int x = sourceBounds.x + (int)(portion*(targetBounds.x - sourceBounds.x));
			int y = sourceBounds.y + (int)(portion*(targetBounds.y - sourceBounds.y));
			int w = sourceBounds.width + (int)(portion*(targetBounds.width - sourceBounds.width));
			int h = sourceBounds.height + (int)(portion*(targetBounds.height - sourceBounds.height));
			setBounds( x, y, w, h );
			repaint();
		} else {
			setVisible( false );
			authoringTool.getScheduler().removeEachFrameRunnable( RectangleAnimator.this );
		}
	}
}
